package huayang.ws;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Created by buhuayang on 16/7/13.
 */
@Controller
public class ChatRoomController {
    @RequestMapping(value = "/toRoom.htm")
    public String toRoom(@RequestParam(value = "username") String username, HttpServletRequest request, Model model) {
        HttpSession session = request.getSession();
        ChatRoomSessionData sessionData = new ChatRoomSessionData();
        sessionData.setHttpSessionId(session.getId());
        sessionData.setUsername(username);
        session.setAttribute("username", username);
        WebContent.httpSessionDataMap.put(sessionData.getHttpSessionId(), sessionData);
        return "chat-room";
    }
    @RequestMapping(value = "/online-list.htm")
    public String onlineList(Model model) {
        List<OnlineInfo> onlineInfoList = new ArrayList<>();
        Set<String> socketSessionMapKeyset = WebContent.socketSessionDataMap.keySet();
        for (String key : socketSessionMapKeyset) {
            ChatRoomSessionData sessionData = WebContent.socketSessionDataMap.get(key);
            WebSocketSession socketSession = sessionData.getSocketSession();
            if (socketSession.isOpen()) {
                OnlineInfo onlineInfo = new OnlineInfo();
                onlineInfo.setHttpSessionId(sessionData.getHttpSessionId());
                onlineInfo.setUsername(sessionData.getUsername());
                onlineInfo.setSocketSessionId(socketSession.getId());
                onlineInfoList.add(onlineInfo);
            }
        }
        model.addAttribute("onlineInfoList", onlineInfoList);
        return "online-list";
    }
}
